import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable

x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], [9.779], [6.182], [7.59], [2.167], [7.042], [10.791],
                    [5.313], [7.997], [3.1]], dtype=np.float32)

y_train = np.array(
    [[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], [3.366], [2.596], [2.53], [1.221], [2.827], [3.465],
     [1.65], [2.904], [1.3]], dtype=np.float32)

# ---------------绘制散点图-----------------
# fig = plt.figure()  # 创建画布
# ax = fig.add_subplot()
# # 添加画布，参数默认111，表示只有1*1的画布，并在第1个画布上绘制
# # 如果参数是221，表示生成2*2块画布，并在第1个画布上绘制
# ax.set(xlim=[1, 12], ylim=[1, 5], title='Show Point', ylabel='Y', xlabel='X')  # 设置画布参数
# plt.scatter(x_train, y_train)  # 绘制散点图，设置点的x，y坐标
# plt.show()  # 展示画布

x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)  # 将x，y转换为张量Tensor类型


# 利用pytorch创建了一个线性回归模型
class LinearRegression(nn.Module):
    def __init__(self):
        super(LinearRegression, self).__init__()
        self.linear = nn.Linear(1, 1)  # 设置输入与输出维度都为1

    def forward(self, x):
        out = self.linear(x)
        return out


model = LinearRegression()
criterion = nn.MSELoss()  # 指定均方误差作为损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)  # 指定优化函数为最简单的梯度下降函数

num_epochs = 1000  # 指定轮数
for epoch in range(num_epochs):
    inputs = Variable(x_train)
    target = Variable(y_train)
    out = model(inputs)
    loss = criterion(out, target)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (epoch + 1) % 20 == 0:
        loss_num = loss.data.numpy()
        print('Epoch:[{}/{}],loss:{:.6f}'.format(epoch + 1, num_epochs, loss_num))

model.eval()  # 将模型变成测试模式
predict = model(Variable(x_train))  # 输入x_train数据通过模型预测得到对应的predict值
predict = predict.data.numpy()  # 输出的预测值是Tensor类型，所以需要转换为numpy类型
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')  # 绘制出实际的点
plt.plot(x_train.numpy(), predict, label='Fitting Line')  # 绘制出预测出的点并连线
plt.show()  # 展示绘制结果
